package com.ckerchina.admin.ckadmin.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ckerchina.admin.ckadmin.controller.dto.ResponseData;
import com.ckerchina.admin.ckadmin.exception.ErrorCode;
import com.ckerchina.admin.ckadmin.exception.ZhuziException;
import com.ckerchina.admin.ckadmin.utils.BeanValidators;

@ControllerAdvice
public class GlobalControllerExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@ExceptionHandler(value = { ZhuziException.class })
	public @ResponseBody ResponseData onBaijimuException(HttpServletRequest request, ZhuziException e) {
		String queryString = request.getQueryString();
		String url = request.getRequestURL().toString() + (StringUtils.isEmpty(queryString) ? "" : "?" + queryString);
		logger.error("请求" + url + "处理异常	errorMessage:" + e.getMessage());
		ResponseData data = new ResponseData(
				e.getErrorCode() == null ? ErrorCode.Internal_Server_Error.value : e.getErrorCode().value, null,
				e.getMessage(), false);
		return data;
	}

	/**
	 * 处理JSR311 Validation异常.
	 */
	@ExceptionHandler(value = { ConstraintViolationException.class })
	public @ResponseBody ResponseData handleException(HttpServletRequest request, ConstraintViolationException e) {
		String queryString = request.getQueryString();
		String url = request.getRequestURL().toString() + (StringUtils.isEmpty(queryString) ? "" : "?" + queryString);
		logger.error("请求" + url + "处理异常 ", e);
		Map<String, String> errors = BeanValidators.extractPropertyAndMessage(e.getConstraintViolations());
		StringBuffer sb = new StringBuffer();
		for (String value : errors.values()) {
			sb.append(value);
		}
		ResponseData data = new ResponseData(ErrorCode.Paramter_Error.value, null, sb.toString(), false);
		return data;
	}

	@ExceptionHandler(value = { Exception.class })
	public @ResponseBody ResponseData onException(HttpServletRequest request, Exception e) {
		String queryString = request.getQueryString();
		String url = request.getRequestURL().toString() + (StringUtils.isEmpty(queryString) ? "" : "?" + queryString);
		logger.error("请求" + url + "处理异常 ", e);
		ResponseData data = new ResponseData(ErrorCode.Internal_Server_Error.value, null, e.getMessage(), false);
		return data;
	}
}
